#include "VerifyGrpc_Client.h"
#include"ConFigMgr.h"

VerifyGrpc_Client::VerifyGrpc_Client() {
	auto& gCfgMgr = ConFigMgr::Inst();
	std::string host = gCfgMgr["VarifyServer"]["Host"];
	std::string port = gCfgMgr["VarifyServer"]["Port"];
	pool_.reset(new RPConPool(5, host, port));
}

void RPConPool::Close() {
	b_stop_ = true;
	cond_.notify_all();

}

std::unique_ptr<VarifyService::Stub> RPConPool::getConnection()
{
	std::unique_lock<std::mutex> lock(mutex_);
	cond_.wait(lock, [this]() {
		if (b_stop_)
			return true;
		return !connection_.empty();
		});

	if (b_stop_)
	{
		return nullptr;
	}
	auto context = std::move(connection_.front());
	connection_.pop();
	return context;
}

RPConPool::~RPConPool() {
	std::lock_guard<std::mutex> lock(mutex_);
	
	Close();

	while (!connection_.empty())
	{
		connection_.pop();
	}
}

void RPConPool::returnConnection(std::unique_ptr<VarifyService::Stub> context) {
	std::lock_guard<std::mutex> lock(mutex_);
	if (b_stop_)
	{
		return;
	}
	connection_.push(std::move(context));
	cond_.notify_one();

}